package com.example.stockholdtrack.data

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.util.*

class StockDataStore(context: Context) {
    private val sharedPreferences: SharedPreferences = context.getSharedPreferences("stock_data", Context.MODE_PRIVATE)
    private val gson = Gson()
    
    private val _stocks = MutableStateFlow<List<StockItem>>(emptyList())
    val stocks: StateFlow<List<StockItem>> = _stocks.asStateFlow()
    
    private val _positionRecords = MutableStateFlow<Map<String, List<PositionRecord>>>(emptyMap())
    val positionRecords: StateFlow<Map<String, List<PositionRecord>>> = _positionRecords.asStateFlow()
    
    init {
        loadStocks()
        loadPositionRecords()
    }
    
    private fun loadStocks() {
        val stocksJson = sharedPreferences.getString("stocks", "[]")
        val type = object : TypeToken<List<StockItem>>() {}.type
        val stocksList = gson.fromJson<List<StockItem>>(stocksJson, type)
        _stocks.value = stocksList ?: emptyList()
    }
    
    private fun loadPositionRecords() {
        val recordsJson = sharedPreferences.getString("position_records", "{}")
        val type = object : TypeToken<Map<String, List<PositionRecord>>>() {}.type
        val recordsMap = gson.fromJson<Map<String, List<PositionRecord>>>(recordsJson, type)
        _positionRecords.value = recordsMap ?: emptyMap()
    }
    
    private fun saveStocks() {
        val stocksJson = gson.toJson(_stocks.value)
        sharedPreferences.edit().putString("stocks", stocksJson).apply()
    }
    
    private fun savePositionRecords() {
        val recordsJson = gson.toJson(_positionRecords.value)
        sharedPreferences.edit().putString("position_records", recordsJson).apply()
    }
    
    fun getAllStocks(): Flow<List<StockItem>> {
        return stocks
    }
    
    // 添加一个同步获取方法
    suspend fun getAllStocksSync(): List<StockItem> {
        // 每次都从SharedPreferences重新加载最新数据
        val stocksJson = sharedPreferences.getString("stocks", "[]")
        val type = object : TypeToken<List<StockItem>>() {}.type
        val stocksList = gson.fromJson<List<StockItem>>(stocksJson, type) ?: emptyList()
        
        // 更新内存中的数据
        _stocks.value = stocksList
        
        return stocksList
    }
    
    suspend fun getStockByCode(code: String): StockItem? {
        return _stocks.value.find { stock -> stock.code == code }
    }
    
    suspend fun insertStock(stock: StockItem) {
        val currentStocks = _stocks.value.toMutableList()
        val existingIndex = currentStocks.indexOfFirst { existingStock -> existingStock.id == stock.id }
        
        if (existingIndex >= 0) {
            currentStocks[existingIndex] = stock
        } else {
            currentStocks.add(stock)
        }
        
        _stocks.value = currentStocks.toList()
        saveStocks()
    }
    
    suspend fun updateStock(stock: StockItem) {
        insertStock(stock)
    }
    
    suspend fun deleteStock(stock: StockItem) {
        val currentStocks = _stocks.value.toMutableList()
        currentStocks.removeAll { existingStock -> existingStock.id == stock.id }
        _stocks.value = currentStocks
        saveStocks()
        
        // 同时删除相关的持仓记录
        val currentRecords = _positionRecords.value.toMutableMap()
        currentRecords.remove(stock.code)
        _positionRecords.value = currentRecords
        savePositionRecords()
    }
    
    fun getPositionRecordsByStockCode(stockCode: String): Flow<List<PositionRecord>> {
        return _positionRecords.map { records -> records[stockCode] ?: emptyList() }
    }
    
    suspend fun insertPositionRecord(record: PositionRecord, stockCode: String) {
        val currentRecords = _positionRecords.value.toMutableMap()
        val stockRecords = currentRecords[stockCode]?.toMutableList() ?: mutableListOf()
        stockRecords.add(record)
        currentRecords[stockCode] = stockRecords
        _positionRecords.value = currentRecords
        savePositionRecords()
        
        // 重新计算股票数据
        recalculateStockData(stockCode)
    }
    
    suspend fun updatePositionRecord(record: PositionRecord, stockCode: String) {
        println("DEBUG: StockDataStore.updatePositionRecord - 要更新的记录 ID: ${record.id}, 数量: ${record.quantity}, 价格: ${record.price}")
        val currentRecords = _positionRecords.value.toMutableMap()
        val stockRecords = currentRecords[stockCode]?.toMutableList() ?: mutableListOf()
        
        println("DEBUG: StockDataStore.updatePositionRecord - 数据存储中的记录:")
        stockRecords.forEachIndexed { index, existingRecord ->
            println("DEBUG: 索引[$index] - ID: ${existingRecord.id}, 数量: ${existingRecord.quantity}, 价格: ${existingRecord.price}")
        }
        
        val index = stockRecords.indexOfFirst { existingRecord -> existingRecord.id == record.id }
        
        println("DEBUG: StockDataStore.updatePositionRecord - 找到的索引: $index, 总记录数: ${stockRecords.size}")
        
        if (index >= 0) {
            stockRecords[index] = record
            currentRecords[stockCode] = stockRecords
            _positionRecords.value = currentRecords
            savePositionRecords()
            
            // 重新计算股票数据
            recalculateStockData(stockCode)
        } else {
            println("DEBUG: StockDataStore.updatePositionRecord - 未找到匹配的记录!")
        }
    }
    
    suspend fun deletePositionRecord(record: PositionRecord) {
        println("DEBUG: StockDataStore.deletePositionRecord - 要删除的记录 ID: ${record.id}, 数量: ${record.quantity}, 价格: ${record.price}")
        val currentRecords = _positionRecords.value.toMutableMap()
        currentRecords.forEach { (stockCode, records) ->
            println("DEBUG: StockDataStore.deletePositionRecord - 检查股票代码: $stockCode, 记录数: ${records.size}")
            val updatedRecords = records.filter { existingRecord -> existingRecord.id != record.id }
            if (updatedRecords.size != records.size) {
                println("DEBUG: StockDataStore.deletePositionRecord - 找到并删除记录")
                currentRecords[stockCode] = updatedRecords
                _positionRecords.value = currentRecords
                savePositionRecords()
                
                // 重新计算股票数据
                recalculateStockData(stockCode)
                return
            }
        }
        println("DEBUG: StockDataStore.deletePositionRecord - 未找到要删除的记录!")
    }
    
    suspend fun recalculateStockData(stockCode: String) {
        val stock = getStockByCode(stockCode) ?: return
        val records = _positionRecords.value[stockCode] ?: emptyList()
        
        val totalQuantity = records.sumOf { record -> record.quantity }
        val totalCost = records.sumOf { record -> record.quantity * record.price }
        val averagePrice = if (totalQuantity > 0) totalCost / totalQuantity else 0.0
        
        println("DEBUG: StockDataStore.recalculateStockData - 股票: ${stock.name}(${stock.code})")
        println("DEBUG: StockDataStore.recalculateStockData - 记录数: ${records.size}")
        println("DEBUG: StockDataStore.recalculateStockData - 总数量: $totalQuantity")
        println("DEBUG: StockDataStore.recalculateStockData - 总成本: $totalCost")
        println("DEBUG: StockDataStore.recalculateStockData - 平均价格: $averagePrice")
        
        val updatedStock = stock.copy(
            quantity = totalQuantity,
            averagePrice = averagePrice
        )
        
        insertStock(updatedStock)
    }
    
    // 新增：重新计算所有股票数据
    suspend fun recalculateAllStockData() {
        println("DEBUG: StockDataStore.recalculateAllStockData - 开始重新计算所有股票数据")
        val allStocks = _stocks.value
        for (stock in allStocks) {
            recalculateStockData(stock.code)
        }
        println("DEBUG: StockDataStore.recalculateAllStockData - 所有股票数据重新计算完成")
    }
} 